package com.atguigu.springcloud.controller;

import com.atguigu.springcloud.entity.Payment;
import com.atguigu.commonutils.R;
import com.atguigu.springcloud.service.PaymentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author cdd
 * @since 2021-03-08
 */
@RestController
@RequestMapping("/payment")
public class PaymentController {

    @Autowired
    private PaymentService paymentService;

    @Autowired
    private DiscoveryClient discoveryClient;

    @Value("${server.port}")
    private String serverPort;

    @PostMapping("create")
    public R create(@RequestBody Payment payment) {
        // 返回添加支付的ID
        Long paymentId = paymentService.create(payment);
        return R.ok().data("paymentId",paymentId).message("server port:" + serverPort);
    }

    @GetMapping("getPaymentById/{id}")
    public R getPaymentById(@PathVariable Long id) {
        Payment payment = paymentService.getById(id);
        return R.ok().data("payment",payment).message("server port:" + serverPort);
    }

    @GetMapping("discoveryInfo")
    public Object discovery(){
        List<String> services = discoveryClient.getServices();  // 注册在服务中心的服务列表
        for (String service :services) {
            System.out.println("========service: " + service);
        }
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PROVIDER-SERVICE");// 查看某个服务的具体信息
        for (ServiceInstance instance:instances) {
            System.out.println(instance.getInstanceId() + "   " + instance.getServiceId() + "  " + instance.getHost());
        }
        return this.discoveryClient;
    }
}

